import { addHospitalSet, getHospitalSetById, updateHospitalSet } from "@/api/hospital/hospitalSet";
import { AddHospitalSetParams } from "@/api/hospital/hospitalSet/types";
import { Button, Card, Form, Input, Space, message } from "antd";
import { useForm } from "antd/lib/form/Form";
import React, { useEffect } from "react";
import { useNavigate, useParams } from "react-router-dom";

export default function AddOrUpdateHospitalSet() {
  //获取 navigate 函数
  let navigate = useNavigate();
  //获取 params 参数
  let {id} = useParams();
  //获得 form 对象
  let [form] = useForm();
  
  //声明onFinish
  let onFinish = async (values: AddHospitalSetParams) => {
    if(id){
      //发送请求
      await updateHospitalSet({
        ...values,
        id: id
      });
      message.success('更新成功');
    }else{
      //发送请求
      await addHospitalSet(values);
      //添加一个成功的提醒
      message.success('添加成功');
    }
    //跳转到医院设置列表
    navigate('/syt/hospital/hospitalSet');
  };
  
  //声明 useEffect
  useEffect(() => {
    let getHospital = async () => {
      //判断
      if(!id) return;
      //发送请求 获取医院的数据
      let result = await getHospitalSetById(id as string);
      //修改表单元素的值
      form.setFieldsValue(result);
    }
    getHospital();
  }, [])

  return (
    <Card>
      <Form
        form={form}
        name="basic"
        labelCol={{ span: 2 }}
        wrapperCol={{ span: 22 }}
        onFinish={onFinish}
        autoComplete="off"
      >
        <Form.Item
          label="医院名称"
          name="hosname"
          rules={[{ required: true, message: "医院名称不能为空" }]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="医院编号"
          name="hoscode"
          rules={[{ required: true, message: "医院编号不能为空" }]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          label="api基础路径"
          name="apiUrl"
          rules={[{ required: true, message: "api基础路径不能为空" }]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          label="联系人姓名"
          name="contactsName"
          rules={[{ required: true, message: "联系人姓名不能为空" }]}
        >
          <Input />
        </Form.Item>
    
        <Form.Item
          label="联系人手机"
          name="contactsPhone"
          rules={[
            { required: true, message: "医院名称不能为空" },
            { pattern: /^1\d{10}$/, message: '手机号格式错误'}
          ]}
        >
          <Input />
        </Form.Item>

        <Form.Item wrapperCol={{ offset: 2, span: 22 }}>
          <Space>
            <Button type="primary" htmlType="submit">
              {id ? '更新' : '新增'}
            </Button>

            <Button>返回</Button>
          </Space>
        </Form.Item>
      </Form>
    </Card>
  );
}
